package com.jlt.baidu.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jlt.baidu.dto.AddresResponse;
import com.jlt.baidu.dto.AddressRequest;
import com.jlt.baidu.dto.DepparserResponse;
import com.jlt.baidu.dto.SimilaryRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * 借用百度AI，自动补全地址匹配 https://ai.baidu.com/tech/nlp_apply/address
 * 
 * 同时支持用户名，电话的自动提取. 5000次/天免费
 * 
 * @author 苹果
 * @date 2019/10/17
 */
@Slf4j
public class BaidduAIUtil {
    static String token = null;

    /**
     * 自动地址补全和捕获，文本长度最长1000
     * 
     * @param address
     * @return
     */
    public static String AddressComplete(AddressRequest address) {
        if (token == null) {
            token = getAuth();
        }
        String uri = "https://aip.baidubce.com/rpc/2.0/nlp/v1/address?charset=UTF-8&access_token=" + token;
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(uri);
        try {
            method.setRequestHeader("Accept", "application/json");
            RequestEntity se = new StringRequestEntity(JSON.toJSONString(address), "application/json", "UTF-8");
            method.setRequestEntity(se);
            client.executeMethod(method);
            if (method.getStatusCode() == 200) {
                // getResponseBodyAsString 方法默认编码ISO-8859-1
                String result = new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"), "utf-8");
                AddresResponse response = JSON.parseObject(result, AddresResponse.class);
                return response.toString();
            }
            return "请求百度相应错误代码：" + method.getStatusCode();
        } catch (IOException e) {
            log.error("请求百度地址接口错误：", e);
        }
        return null;
    }

    /**
     * 计算文本相似度
     * 
     * @param request
     */
    public static String textSimilaryPrecent(SimilaryRequest request) {
        if (token == null) {
            token = getAuth();
        }
        String uri = "https://aip.baidubce.com/rpc/2.0/nlp/v2/simnet?charset=UTF-8&access_token=" + token;
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(uri);
        try {
            method.setRequestHeader("Accept", "application/json");
            RequestEntity se = new StringRequestEntity(JSON.toJSONString(request), "application/json", "UTF-8");
            method.setRequestEntity(se);
            client.executeMethod(method);
            if (method.getStatusCode() == 200) {
                // getResponseBodyAsString 方法默认编码ISO-8859-1
                String result = new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"), "utf-8");
                return result;
            }
            return "请求百度相应错误代码：" + method.getStatusCode();
        } catch (IOException e) {
            log.error("请求百度计算文本相似接口错误：", e);
        }
        return null;
    }

    /**
     * 测试百度AI的词法分析接口
     * 
     * @param text
     * @return
     */
    public static String testLexerFunction(String text) {
        if (token == null) {
            token = getAuth();
        }
        String uri = "https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?charset=UTF-8&access_token=" + token;
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(uri);
        try {
            method.setRequestHeader("Accept", "application/json");
            JSONObject param = new JSONObject();
            param.put("text", text);
            RequestEntity se = new StringRequestEntity(param.toJSONString(), "application/json", "UTF-8");
            method.setRequestEntity(se);
            client.executeMethod(method);
            if (method.getStatusCode() == 200) {
                // getResponseBodyAsString 方法默认编码ISO-8859-1
                String result = new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"), "utf-8");
                return result;
            }
            return "请求百度相应错误代码：" + method.getStatusCode();
        } catch (IOException e) {
            log.error("请求百度计算文本相似接口错误：", e);
        }
        return null;
    }

    /**
     * 测试百度AI的依存句法分析接口
     * 
     * @param text
     * @return
     */
    public static List<DepparserResponse> testDepparserFunction(String text) {
        if (token == null) {
            token = getAuth();
        }
        String uri = "https://aip.baidubce.com/rpc/2.0/nlp/v1/depparser?charset=UTF-8&access_token=" + token;
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(uri);
        try {
            method.setRequestHeader("Accept", "application/json");
            JSONObject param = new JSONObject();
            param.put("text", text);
            param.put("mode", 0);
            RequestEntity se = new StringRequestEntity(param.toJSONString(), "application/json", "UTF-8");
            method.setRequestEntity(se);
            client.executeMethod(method);
            if (method.getStatusCode() == 200) {
                // getResponseBodyAsString 方法默认编码ISO-8859-1
                String result = new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"), "utf-8");
                JSONObject object = JSONObject.parseObject(result);
                List<DepparserResponse> jsonResult =
                    JSON.parseArray(object.getString("items"), DepparserResponse.class);
                return jsonResult;
            }
        } catch (IOException e) {
            log.error("请求百度计算文本相似接口错误：", e);
        }
        return null;
    }

    private static String getAuth() {
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
            // 1. grant_type为固定参数
            + "grant_type=client_credentials"
            // 2. 官网获取的 API Key
            + "&client_id="
            // 3. 官网获取的 Secret Key
            + "&client_secret=";
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

}
